package cd.safe.school.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cd.safe.school.R;
import cd.safe.school.adapter.CustomizedAdapter;
import cd.safe.school.adapter.StudentDetailAdapter;
import cd.safe.school.bean.Student;
import cd.safe.school.data.StudentData;
import cd.safe.school.ui.MyDialog;
import cd.safe.school.util.HztoPy;
import cd.safe.school.util.ListItemData;
import cd.safe.school.util.Parse;
import cd.safe.school.util.SharedPreUtil;

public class MainActivity extends Activity implements OnCheckedChangeListener {
	// 全选/反选
	private CheckBox allsearch;
	// 搜索条件输入框
	// 标识列表信息
	public static int tog = 1;
	private EditText search_edit;

	private static TextView liebiao;
	private Button search;
	private static ListView student_data;
	private static CustomizedAdapter adapter;
	private StudentData sd;
	private SQLiteDatabase db;
	private String deptid = "";
	private MyDialog dialog;
	public static Handler handler;
	private Handler handler2 = new Handler();
	private ProgressDialog pd;

	private HztoPy py = new HztoPy();
	private static List<ListItemData> lists = new ArrayList<ListItemData>();
	private List<Student> students = new ArrayList<Student>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		SharedPreUtil.addActivity(this);
		// String uername = getIntent().getStringExtra("username");
		// String password = getIntent().getStringExtra("password");
		// dialog = new MyDialog(MainActivity.this, handler);
		sd = new StudentData(this);
		allsearch = (CheckBox) findViewById(R.id.allsearch);
		search_edit = (EditText) findViewById(R.id.search_edit);
		search = (Button) findViewById(R.id.search);
		student_data = (ListView) findViewById(R.id.student_data);
		db = sd.getWritableDatabase();
		liebiao = (TextView) findViewById(R.id.liebiao);

		student_data.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				pd.show();
				// System.out.println(student_data.getChildCount());
				// boolean a =
				// CustomizedAdapter.list.get(position).isSelected();
				//
				// if (a) {
				// CustomizedAdapter.list.get(position).setSelected(false);
				//
				// } else {
				// CustomizedAdapter.list.get(position).setSelected(true);
				// }
				HomeActivity.rutn = 5;
				if (lists.size() > 0) {
					deptid = lists.get(position).getDeptid();
					lists.clear();
					if (tog == 1) {

						liebiao.setText("年级列表");

						lists = Parse.parseschool(deptid);
						if (lists.size() > 0)
							tog = 2;
					} else if (tog == 2) {

						liebiao.setText("学生列表");
						lists = Parse.parseschool(deptid);
						if (lists.size() > 0)
							tog = 3;

					} else if (tog == 3) {

					}

					pd.hide();

					if (lists.size() == 0) {
						Toast.makeText(MainActivity.this, "获取数据失败...",
								Toast.LENGTH_SHORT).show();
					}
				}
				adapter.notifyDataSetChanged();

			}

		});
		pd = ProgressDialog.show(MainActivity.this, "", "数据加载...");
		pd.setCancelable(true);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 设置学校列表
				lists = Parse.parseschool("");
				handler2.post(new Runnable() {

					@Override
					public void run() {
						pd.hide();

						if (lists.size() > 0) {
							adapter = new CustomizedAdapter(MainActivity.this,
									lists);
							student_data.setAdapter(adapter);
						} else {
							Toast.makeText(MainActivity.this, "获取数据失败...",
									Toast.LENGTH_SHORT).show();

						}

					}
				});

			}
		}).start();

		adapter = new CustomizedAdapter(this, lists);
		student_data.setAdapter(adapter);
		allsearch.setOnCheckedChangeListener(this);
		search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String tx = search_edit.getText().toString();
				String y = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

				if (y.contains(tx)) {
					String selector = "shouzimu like ?";
					Cursor cursor = db.query("student", null, selector,
							new String[] { "%" + tx + "%" }, null, null, null);
					if (cursor != null) {
						while (cursor.moveToNext()) {
							setstudent(cursor);

						}

						cursor.close();
					} else {
						Toast.makeText(MainActivity.this, "未查询到",
								Toast.LENGTH_SHORT).show();
					}

				} else if (isnumber(tx)) {
					String selector = "phone like ?";
					Cursor cursor = db.query("student", null, selector,
							new String[] { tx + "%" }, null, null, null);
					if (cursor != null) {
						while (cursor.moveToNext()) {
							setstudent(cursor);

						}

					} else {
						Toast.makeText(MainActivity.this, "未查询到",
								Toast.LENGTH_SHORT).show();

					}
					cursor.close();

				} else if (ishanzi(tx)) {
					String selector = "name like ?";
					Cursor cursor = db.query("student", null, selector,
							new String[] { "%" + tx + "%" }, null, null, null);
					if (cursor != null) {
						while (cursor.moveToNext()) {
							setstudent(cursor);
						}

					} else {
						Toast.makeText(MainActivity.this, "未查询到",
								Toast.LENGTH_SHORT).show();
					}
					cursor.close();
				} else {
					Toast.makeText(MainActivity.this, "输入字符不合法",
							Toast.LENGTH_SHORT).show();
				}
				adapter.notifyDataSetChanged();

			}

		});
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.allsearch:
			if (isChecked) {
				for (int i = 0; i < lists.size(); i++) {
					CustomizedAdapter.list.get(i).setSelected(true);
				}

			} else {
				for (int i = 0; i < lists.size(); i++) {
					CustomizedAdapter.list.get(i).setSelected(false);
				}

			}
			adapter.notifyDataSetChanged();

			break;

		default:
			break;
		}

	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	// 判断是否为数字
	public boolean isnumber(String num) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher m = pattern.matcher(num);
		if (!m.matches()) {
			return false;
		}
		return true;
	}

	// 判断是否为汉字
	public boolean ishanzi(String str) {

		char[] chars = str.toCharArray();
		boolean ishanzi = true;
		for (int i = 0; i < chars.length; i++) {
			byte[] bytes = ("" + chars[i]).getBytes();
			if (bytes.length == 2) {
				int[] ints = new int[2];
				ints[0] = bytes[0] & 0xff;
				ints[1] = bytes[1] & 0xff;
				if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40
						&& ints[1] <= 0xFE) {
					ishanzi = false;
					break;
				}
			}
		}
		return ishanzi;
	}

	private void setstudent(Cursor cursor) {
		Student s = new Student();
		String name = cursor.getString(cursor.getColumnIndex("name"));
		String phone = cursor.getString(cursor.getColumnIndex("phone"));
		String logurl = cursor.getString(cursor.getColumnIndex("logurl"));
		String lastlogin = cursor.getString(cursor.getColumnIndex("lastlogin"));
		int age = cursor.getInt(cursor.getColumnIndex("age"));
		s.setAge(age);
		s.setLastlogin(lastlogin);
		s.setLogurl(logurl);
		s.setName(name);
		s.setPhone(phone);
		students.add(s);

	}

	// public static void reset() {
	//
	//
	// lists.clear();
	// liebiao.setText("学生列表");
	// int count = student_data.getChildCount();
	// if (count > 0) {
	// for (int i = 0; i < count; i++) {
	// LinearLayout rlay = (LinearLayout) student_data.getChildAt(i);
	// CheckBox cb = (CheckBox) rlay.findViewById(R.id.student_search);
	// if (cb.isChecked()) {
	// for (int j = 0; j < 10; j++) {
	// Student sd = new Student();
	// sd.setName("zhangsan");
	// ListItemData li = new ListItemData(sd);
	//
	// lists.add(li);
	//
	// }
	//
	// }
	//
	// }
	//
	// }
	// adapter.notifyDataSetChanged();
	// }
	//
	// public static void ret() {
	//
	// liebiao.setText("班级列表");
	// lists.clear();
	// // for (int i = 0; i < 10; i++) {
	// // lists.add(new ListItemData("一年级" + i + "班"));
	// // }
	// adapter.notifyDataSetChanged();
	// }

	public static List<ListItemData> getdata() {
		List<ListItemData> list = new ArrayList<ListItemData>();
		int count = lists.size();
		if (count > 0) {
			for (int i = 0; i < count; i++) {
				if (CustomizedAdapter.list.get(i).isSelected()) {
					ListItemData li = lists.get(i);

					list.add(li);
				}

			}
		}

		return list;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

}